/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 08 - 23
 * Time: 10:38
 */
//牛客 链表中倒数第k个结点
public class Solution3 {
    //法一
    public ListNode FindKthToTail1 (ListNode pHead, int k) {
        if(pHead == null) return null;
        if(k == 0) return null;
        ListNode fast = pHead;
        ListNode slow = pHead;
        for(int i = 0; i < k - 1; i++) {//注意条件是i<k-1，先把快指针和慢指针的距离拉开
            fast = fast.next;
            if(fast == null) return null;
        }
        while(fast.next != null) {//注意条件是fast.next!=null
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

    //法二
    public ListNode FindKthToTail2 (ListNode pHead, int k) {
        if(pHead == null) return null;
        ListNode fast = pHead;
        ListNode slow = pHead;
        for(int i = 0; i < k; i++) {//注意条件是i<k，先把快指针和慢指针的距离拉开
            if(fast != null) {
                fast = fast.next;//fast=fast.next后当fast为null时刚好跳出循环（因为此时i==k-1)，所以不会return null
            }else {
                return null;
            }
        }
        while(fast != null) {//注意条件是fast!=null
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
